package com.lgy.service;

import com.lgy.config.EsConfig;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class EsliveDeptPanelNewService {
    public List<Map<String,Object>> findAllEsData(String dayTime, Integer flag) {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        boolQueryBuilder.must(QueryBuilders.rangeQuery("createTime").gte(dayTime).format("yyyy-MM-dd"));
        boolQueryBuilder.must(QueryBuilders.rangeQuery("createTime").lte(dayTime).format("yyyy-MM-dd"));
        if(null != flag) {
            //为为查询所有数据
            boolQueryBuilder.must(QueryBuilders.termQuery("flag", 1));
        }
        SearchHit[] hits;
        SearchRequest request = new SearchRequest("live_dept_panel_new");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(boolQueryBuilder);//查询参数
        sourceBuilder.size(100000);
        request.source(sourceBuilder);
        try {
            hits = EsConfig.getEsInstance().search(request, RequestOptions.DEFAULT).getHits().getHits();
            List<Map<String,Object>> map = new ArrayList<>();
            for(SearchHit hit : hits) {
                Map<String,Object> temp = hit.getSourceAsMap();
                temp.put("_id", hit.getId());
                map.add(temp);
            }
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
